﻿using System;
using System.Text;
using System.Collections;
using RAP.Framework.Libary.DomTemplateBuilder.Interface;
using RAP.Framework.Libary.Utils;
using RAP.Framework.Libary.DomTemplateBuilder.Element.Collection;

namespace RAP.Framework.Libary.DomTemplateBuilder.Handler
{
	/// <summary>
	/// 迭代器的Handler
	/// </summary>
	public class InnerJoinIterateHandler : IterateHandler
	{
		public new InnerJoinIterate Element
		{
			get
			{
				return base.Element as InnerJoinIterate;
			}
		}

		protected string[ ] _innerPropertyList = null;
		protected char[ ] _propertyValueSplitChars = new char[ ] { ',' };
		protected char[ ] _propertyNameSplitChars = new char[ ] { '|' };
		/// <summary>
		/// 获取多个属性
		/// </summary>
		public string[ ] InnerProperty
		{
			get
			{
				if ( _innerPropertyList == null )
				{
					var innerProperty = this.Element.InnerProperty;
					if ( innerProperty.IndexOfAny ( _propertyNameSplitChars ) > 0 )
					{
						_innerPropertyList = innerProperty.Split ( _propertyNameSplitChars, StringSplitOptions.RemoveEmptyEntries );
					}
					else if ( !innerProperty.IsNullOrEmpty ( ) )
					{
						_innerPropertyList = new string[ ] { innerProperty };
					}
					else
					{
						_innerPropertyList = new string[ ] { };
					}
				}
				return _innerPropertyList;
			}
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="writer"></param>
		/// <param name="rootParamObject"></param>
		/// <param name="parentParamObject"></param>
		/// <param name="context"></param>
		/// <returns></returns>
		public override void DoRender ( StringBuilder writer, object rootParamObject, object parentParamObject, ITemplateRenderContext context )
		{
			var listA = this.GetPropertyListValue ( this.Property, rootParamObject, parentParamObject, context );
			IList listB = null;
			var innerPropoerty = this.Element.InnerProperty;
			if ( innerPropoerty.IndexOfAny ( _propertyValueSplitChars ) > 0 )
			{
				listB = innerPropoerty.Split ( _propertyValueSplitChars );
			}
			else
			{
				listB = this.GetPropertyListValue ( this.InnerProperty, rootParamObject, parentParamObject, context );
			}
			
			if ( listA == null || listA.Count == 0 )
			{
				return;
			}
			IList list = new ArrayList ( );
			if ( listB != null && listB.Count > 0 )
			{
				//取出listA和listB中同时拥有的项
				var joinField = this.Element.JoinField;
				for ( var i = 0; i < listA.Count; i++ )
				{
					var valueA = listA[ i ];
					for ( var j = 0; j < listB.Count; j++ )
					{
						var valueB = listB[ j ];
						if ( valueB != null )
						{
							if ( valueA.GetValue ( joinField ).Equals ( valueB.GetValue ( joinField ) ) )
							{
								list.Add ( valueA );
								break;
							}
						}
					}
				}
			}
			else
			{
				list = listA;
			}
			this.RenderCollection ( writer, list, rootParamObject, parentParamObject, context );
		}
	}
}
